from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet

from bugs.models import Bug, BugHandle
from bugs.serializers import BugSerializer, BugHandleSerializer


class BugViewSet(viewsets.ModelViewSet):
    queryset = Bug.objects.all().filter(is_deleted=False)
    serializer_class = BugSerializer
    permission_classes = [IsAuthenticated]
    filterset_fields = ['interface', 'project']  # noqa
    ordering = ['-create_time']  # 默认排序方式

    def perform_destroy(self, instance):
        instance.is_deleted = True
        instance.save()

    def perform_create(self, serializer):
        user = self.request.user
        instance = serializer.save(user=user)
        BugHandle.objects.create(bug=instance, update_user=user, handle=f"提交bug，状态为【{instance.status}】")

    def perform_update(self, serializer):
        user = self.request.user
        # 不更新bug的提交者
        instance = serializer.save()
        BugHandle.objects.create(bug=instance, update_user=user, handle=f"更新bug，状态为【{instance.status}】")

class BugHandleViewSet(mixins.ListModelMixin,
                       GenericViewSet):
    queryset = BugHandle.objects.all()
    serializer_class = BugHandleSerializer
    permission_classes = [IsAuthenticated]
    filterset_fields = ['bug']  # noqa
    ordering = ['-create_time']  # 默认排序方式
